#coding=utf-8
import requests,json,time,re,sys,copy
reload(sys)
sys.setdefaultencoding("utf-8")

users={
	# '张王留':'17625927017',
	# '尤瑞':'18951295158',
	'高升':'15651795325',
}

class Eleme:


	paohui={
		'sign':'7b8096f804a0f0b01327a5d950a83616',
		'wx':'oEGLvjhSx0-fcAg2qS9etClesg5I',
	}

	lingqu={
		'sign':'eaa89f28aa1ac11bd478a4f5b99930c5',
		'wx':'oEGLvjmb4UzByP9vLfaLeZf5gFBA',
	}

	def run(self):
		global users
		self.set_phone(users[self.name])
		hi=1
		while True:
			print "正在帮"+self.name+"抢第"+str(hi)+"个红包"
			C=False
			B=False
			sns=self.get_sn_from_web()
			
			while True:
				sns_temp=copy.deepcopy(sns)
				for sn in sns:
					num=self.qiang(sn,self.paohui)['num']
					print "更新:"+sn+" 金额:"+str(sns[sn]['luck'])+" 当前人数:"+str(num)
					if num>=sns[sn]['luck']:
						del sns_temp[sn]
					elif num+1==sns[sn]['luck']:
						status=self.qiang(sn,self.lingqu)
						if status.has_key('money'):
							print "恭喜"+self.name+" 抢到了"+str(status['money'])+"元红包"
							B=True
							break
						elif status['code']==5:
							print self.name+"今天已经抢了太多红包"
							return
				if B:break	
				sns=sns_temp
				if not sns:
					C=True
					break
				
			if C:continue
			hi+=1
			if hi>5:break

	def manual(self,sn):
		global users
		self.set_phone(users[self.name])
		luck=self.get_luck(sn)
		while True:
			num=self.qiang(sn,self.paohui)['num']
			print "更新:"+sn+" 金额:"+str(luck)+" 当前人数:"+str(num)
			if num>=luck:
				print "指定sn已经无效"
				return
			if num+1==luck:
				status=self.qiang(sn,self.lingqu)
				if status['code']==5:
					print self.name+"今天已经抢了太多红包"
					return
				if status.has_key('money'):
					print "恭喜"+self.name+" 抢到了"+str(status['money'])+"元红包"
					return
	
	def __init__(self,name,auto_sn=None):
		self.name=name
		if not auto_sn:
			self.run()
		else:
			self.manual(auto_sn)

	def get_luck(self,sn):
		url="https://restapi.ele.me/marketing/themes/1313/group_sns/"+sn
		r=requests.get(url).text
		r=json.loads(r)
		luck=re.findall(u'第([0-9]+)个',r['title'])
		if not luck:return 0
		return int(luck[0])

	def set_phone(self,phone):
		url="https://restapi.ele.me/v1/weixin/oEGLvjgZY8zyv21b53cW-BfP0siw/phone"
		data={
			'sign':'a29f235a9757686fbfea43a5ff8b2484',
			'phone':str(phone),	
		}
		r=requests.put(url,data=json.dumps(data))


	def qiang(self,sn,u):
		url="https://restapi.ele.me/marketing/promotion/weixin/"+u['wx']
		data={
			"method": "phone",
			"platform": 0,
			"group_sn": sn,
			"sign": u['sign'],
			"weixin_username": "ChenWei",
			"latitude": 31.99573,
			"unionid": "o_PVDuNtgppqV-KrNrqtZ9wVHeBw",
			"group_sn": "1d4aac7a4131243b",
			"weixin_avatar": "http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/DYAIOgq83eruPvU6dkYFTCOwBmshyAV3koPaZKjKKrVMm16iaGib8GAaIbvM9nSAK3hn9ibzotUoYjSENKlEhFwow\/132"
		}
		while True:
			r=requests.post(url,data=json.dumps(data)).text
			r=json.loads(r)
			if r.has_key('name') and r['name']=='TOO_BUSY':
				time.sleep(0.1)
				continue
			result={
				'num':len(r['promotion_records']),
				'code':r['ret_code'],
			}
			if len(r['promotion_items']):
				result['money']=r['promotion_items'][0]['amount']
			return result

	def get_sn_from_web(self):
		# https: // h5.ele.me / hongbao /?theme_id = 4363 & is_lucky_group = True & lucky_number = 0 & sn = 1
		# d4ab2ec4d323c58 & total_count = 15
		print "正在从网络中收集手气红包..."
		url="http://share.jfqnet.com/coupon/2"
		while True:
			r=requests.get(url).content
			urls=re.findall('(/coupon/redirect/[^"]+)',r)
			sns={}
			for url in urls:
				url="http://share.jfqnet.com"+url
				r=requests.get(url)
				try:
					sn=r.url.split("&")[-3].split('=')[1]
					luck=self.get_luck(sn)
					num=self.qiang(sn,self.paohui)['num']
					if num>=luck:continue
					sns[sn]={
						'luck':luck
					}
				except:
					continue
			if not sns:
				print "暂时没有可用红包 30秒后重试"
				time.sleep(30)
				continue
			else:
				break
		return sns

if __name__ == "__main__":
	if len(sys.argv)==1:
		for name in users:
			Eleme(name)
	else:
		if not users.has_key(sys.argv[1]):
			print "无此用户"
			exit()
		if len(sys.argv)==2:
			Eleme(sys.argv[1])
		elif len(sys.argv)==3:
			Eleme(sys.argv[1],sys.argv[2])

